package gui.image;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author SUCCESS\quannguyen
 */
public class AlbumImageList extends ImageList {

    public AlbumImageList(File file, String name) {
        super(file, name);
    }

    @Override
    public void scan() {
        List<File> listImage = new ArrayList<>();
        if (file.exists()) {
            try {
                BufferedReader br = new BufferedReader(new FileReader(file));
                String line;
                while ((line = br.readLine()) != null) {
                    File image = new File(line);
                    if (image.exists()) {
                        listImage.add(image);
                    }
                }
                this.files = listImage;
            } catch (IOException ex) {
                Logger.getLogger(AlbumImageList.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    @Override
    public void removeImage(ImagePanel imagePanel) throws IOException {
        this.jPanelImage.remove(imagePanel);
        util.Function.removeLineFromFile(file, imagePanel.getFile().getPath());
    }

    @Override
    public void addImage(ImagePanel imagePanel) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file, true));
        try (PrintWriter out = new PrintWriter(bufferedWriter)) {
            out.println(imagePanel.getFile().getPath());
        }
        this.jPanelImage.add(imagePanel);
        this.jPanelImage.updateUI();
    }
}
